import req from "@/views/user/list/add/api/index"
import { getDeclareInfo } from "@/api/public"
// 合计
const sumNum = (list, field) => {
  let count = 0
  list.forEach((item) => {
    count += Number(item[field] || 0)
  })
  count = count.toFixed(2)
  return count
}

// 弹窗表格详情弹窗配置
export const dialogTabelInfoConfig = {
  // 库存信息
  inventory: {
    title: "库存信息",
    loadApi: req.ownerInventory,
    tableOptions: {
      border: true,
      columns: [
        { field: "warehouse_name", title: "仓库名称" },
        { field: "wms_attribute_cn", title: "仓库属性", width: "100" },
        { field: "asin", title: "ASIN", width: "120" },
        { field: "owner_name", title: "货主", width: "180" },
        { field: "num", title: "可用库存", width: "90" },
        { field: "lock_num", title: "锁定库存", width: "90" },
        { field: "transit_num", title: "在途库存", width: "90" },
      ],
      data: [],
    },
  },
  // 申报信息
  declare: {
    title: "申报信息",
    api: getDeclareInfo,
    params: {},
    tableOptions: {
      border: true,
      columns: [
        {
          field: "customer_order_no",
          title: "订单号\n包裹单号",
          width: 100,
        },
        { field: "channel_name", title: "运输方式", width: 100 },
        {
          field: "op_content",
          title: "真实追踪号\n物流商单号",
          minWidth: 145,
          slots: {
            default: ({ row }) => {
              return `${row.package_number}\n${row.logistics_api_number}`
            },
          },
        },
        { field: "declare_total_price", title: "订单申报总价", width: 84 },
        { field: "declare_tax", title: "关税", width: 100 },
        { field: "declare_total_weight", title: "申报总重量", width: 90 },
        { field: "sku", title: "申报SKU\n自定义SKU", width: 120 },
        {
          field: "declare_name",
          title: "申报中文名\n申报英文名",
          width: 220,
          slots: {
            default: ({ row }) => {
              return `${row.declare_name}\n${row.declare_en_name}`
            },
          },
        },
        { field: "hs_code", title: "报关编码", width: 82 },
        { field: "declare_price", title: "申报单价", width: 82 },
        { field: "declare_weight", title: "申报重量", width: 80 },
        { field: "declare_quantity", title: "申报数量", width: 80 },
        { field: "declare_rule_name", title: "申报规则", width: 80 },
      ],
    },
  },
  // 订单店铺销售数据列表
  shopSaleList: {
    title: "店铺销售数据",
    loadApi: req.orderShopSaleList,
    closeText: "关闭",
    tableOptions: {
      border: true,
      scrollY: { enabled: true },
      height: "660px",
      columns: [
        { field: "platform", title: "平台" },
        { field: "site", title: "站点", width: "100" },
        { field: "shop", title: "店铺" },
        { field: "sale_num", title: "订单数量", width: "100", sortable: true },
        { field: "sale_amount_us", title: "订单销售额（USD）", width: "180", sortable: true },
        { field: "sale_amount", title: "订单销售额（RMB）", width: "180", sortable: true },
      ],
      data: [],
      showFooter: true,
      footerMethod({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (column.field == "sale_num") {
              return Number(sumNum(data, column.field))
            } else if ("sale_amount_us,sale_amount".includes(column.field)) {
              return sumNum(data, column.field)
            } else if (column.field == "platform") {
              return "合计"
            }
          }),
        ]
      },
    },
  },

  // 二手维修编号
  repairNumber: {
    title: "二手维修编号",
    closeText: "关闭",
    tableOptions: {
      border: true,
      columns: [
        { field: "sku", title: "系统SKU" },
        { field: "repair_number", title: "二手维修编号" },
        { field: "quantity", title: "数量" },
      ],
      data: [],
    },
  },
}

// 订单状态 显示隐藏
export const orderStatusShow = ref(true)
// 高级搜索表单
export const highFieldList = reactive([
  {
    type: "title",
    label: "订单信息",
    style: { width: "100%" },
  },
  { type: "br" },
  { type: "br" },
  { field: "order_type", type: "select", origin: "order_type", options: { placeholder: "订单类型" }, style: { width: "200px" } },
  { field: "is_remark", type: "select", originField: "booleanOption", options: { placeholder: "是否有订单备注" }, style: { width: "200px" } },
  {
    field: "new_order_reason",
    type: "select",
    origin: "new_order_reason",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "新建订单原因" },
    style: { width: "200px" },
  },
  {
    field: "mark_shipping_type",
    type: "select",
    origin: "mark_shipment_type",
    options: { placeholder: "标记发货类型" },
    multiple: true,
    collapseTags: true,
    style: { width: "200px" },
  },
  {
    // field: "strategy_schedule_id",
    slot: "ExecuteOrderStrategy",
    // label: "订单排程策略",
  },
  {
    // field: "is_execute_splitting_strategy",
    slot: "ExecutSplittingStrategy",
    // label: "分仓策略",
  },
  // {
  //   field: "platform_order_type",
  //   type: "select",
  //   origin: "platform_order_type",
  //   multiple: true,
  //   collapseTags: true,
  //   style: { width: "160px" },
  //   options: { placeholder: "平台订单类型" },
  // },

  {
    field: "platform_order_type",
    type: "selectV2",
    origin: "platform_order_type",
    style: { width: "160px" },
    options: { placeholder: "平台订单类型" },
  },

  {
    field: "delivery_time_limit",
    type: "select",
    scriptParams: true,
    options: {
      placeholder: "剩余发货时间",
      data: [
        { label: "已超时", value: { script: "<", val: "0" } },
        { label: "小于6小时", value: { script: "<", val: "6", default: { operate: ">", val: "0" } } },
        { label: "小于12小时", value: { script: "<", val: "12", default: { operate: ">", val: "0" } } },
        { label: "小于1天", value: { script: "<", val: "24", default: { operate: ">", val: "0" } } },
        { label: "小于2天", value: { script: "<", val: "48", default: { operate: ">", val: "0" } } },
        { label: "小于3天", value: { script: "<", val: "72", default: { operate: ">", val: "0" } } },
        { label: "小于4天", value: { script: "<", val: "96", default: { operate: ">", val: "0" } } },
        { label: "小于5天", value: { script: "<", val: "120", default: { operate: ">", val: "0" } } },
        { label: "大于5天", value: { script: ">", val: ">120" } },
      ],
    },
    itemProps: { valueKey: "val" },
    style: { width: "246px" },
  },
  {
    field: "documentary_time",
    type: "select",
    options: {
      placeholder: "跟单时间",
      data: [
        { label: "2天前未发货", value: "2" },
        { label: "5天前未发货", value: "5" },
        { label: "7天前未发货", value: "7" },
        { label: "10天前未发货", value: "10" },
        { label: "15天前未发货", value: "15" },
      ],
    },
    special: true,
    style: { width: "246px" },
  },
  { field: "is_consolidate_order", type: "select", originField: "booleanOption", options: { placeholder: "是否合并订单" }, style: { width: "172px" } },
  { field: "is_split_order", type: "select", originField: "booleanOption", options: { placeholder: "是否拆分订单" }, style: { width: "160px" } },
  { field: "shipping_status", type: "select", origin: "shipping_status", options: { placeholder: "发货状态" }, style: { width: "160px" } },
  { field: "settlement_status", type: "select", origin: "settlement_status", options: { placeholder: "结算状态" }, style: { width: "160px" } },
  {
    field: "is_logistics_reconciliation",
    type: "select",
    options: {
      placeholder: "物流对账",
      data: [
        { label: "已对账", value: 1 },
        { label: "未对账", value: 0 },
      ],
    },
    style: { width: "160px" },
  },
  { field: "refund_status", type: "select", origin: "order_refund_status", options: { placeholder: "退款状态" }, style: { width: "168px" } },
  { type: "title", label: "订单费用" },
  {
    field: "original_order_currency",
    type: "select",
    originField: "countryOpt",
    options: { placeholder: "订单币种" },
    style: { width: "160px" },
  },
  { field: "original_order_amount_cny", prepend: "订单金额", type: "numberRange", suffix: "RMB", precision: 2, style: { width: "344px" } },
  { field: "order_amount", prepend: "产品总价", type: "numberRange", suffix: "RMB", precision: 2, style: { width: "336px" } },
  { field: "shipping_revenue", prepend: "运费收入", type: "numberRange", suffix: "RMB", precision: 2, style: { width: "288px" } },
  {
    field: "order_profit",
    prepend: "订单利润",
    type: "numberRange",
    suffix: "RMB",
    min: -999999,
    precision: 2,
    style: { width: "288px" },
  },
  {
    field: "order_profitability",
    prepend: "订单利润率",
    type: "numberRange",
    suffix: "%",
    min: -99999,
    // max: 100,
    precision: 2,
    style: { width: "308px" },
  },

  { type: "title", label: "产品信息" },
  { field: "estimated_weight", prepend: "订单产品重量", type: "numberRange", suffix: "g", style: { width: "348px" } },
  { field: "order_product_num", prepend: "产品总数", type: "numberRange", style: { width: "268px" } },
  { field: "sku_num", prepend: "SKU总数", type: "numberRange", style: { width: "268px" } },

  {
    field: "is_combination_product_included",
    type: "select",
    originField: "booleanOption",
    options: { placeholder: "是否包含组合产品" },
    style: { width: "188px" },
  },
  {
    field: "timeRangeProducts",
    // label: "时间",
    type: "dateTimeRangeNorm",
    select: [
      { label: "产品添加时间", value: "products.product_added_time" },
      { label: "产品审核时间", value: "products.logistics_review_time" },
    ],
    style: { width: "208px" },
    selectStyle: { width: "128px" },
  },
  {
    field: "products.sales_status",
    type: "select",
    multiple: true,
    collapseTags: true,
    originField: "productStatusTextOpt",
    options: { placeholder: "SKU销售状态" },
    style: { width: "162px" },
  },
  // 产品分类
  { field: "products.categories", type: "select", slot: "SpuCategory", style: { width: "340px" } },
  {
    field: "products.logistics_attributes",
    type: "select",
    multiple: true,
    collapseTags: true,
    originField: "logistics_attributes",
    options: { placeholder: "产品物流属性" },
    style: { width: "240px" },
  },
  {
    field: "products.product_level",
    type: "select",
    multiple: true,
    collapseTags: true,
    origin: "product_level",
    options: { placeholder: "产品等级" },
    style: { width: "162px" },
  },

  { type: "title", label: "包裹信息" },
  { field: "recipient_name", placeholder: "收件人姓名", style: { width: "280px" } },
  { field: "recipient_email", placeholder: "收件人邮箱", style: { width: "280px" } },
  { field: "recipient_zip_code", placeholder: "收件人邮编", style: { width: "280px" } },
  { field: "recipient_phone", placeholder: "收件人电话", style: { width: "280px" } },
  { field: "recipient_province", placeholder: "州/省", style: { width: "280px" } },
  { field: "recipient_city", placeholder: "城市", style: { width: "280px" } },
  { field: "recipient_region", placeholder: "区/县", style: { width: "280px" } },
  {
    field: "tracking_number_expiry_date",
    type: "select",
    options: {
      placeholder: "追踪号有效期",
      data: [
        { label: "已过期", value: { script: "<", val: "0" } },
        { label: "小于1天", value: { script: "<", val: "1" } },
        { label: "小于3天", value: { script: "<", val: "3" } },
        { label: "小于5天", value: { script: "<", val: "5" } },
        { label: "小于10天", value: { script: "<", val: "10" } },
        { label: "小于15天", value: { script: "<", val: "15" } },
        { label: "大于15天", value: { script: ">", val: ">15" } },
      ],
    },
    itemProps: { valueKey: "val" },
    scriptParams: true,
    style: { width: "280px" },
  },
  {
    field: "warehouse_type",
    type: "select",
    multiple: true,
    collapseTags: true,
    originField: "wmsAttribute",
    options: { placeholder: "仓库类型" },
    style: { width: "280px" },
  },

  // 平台运输方式
  {
    field: "platform_shipping_method_id",
    slot: "ShippingMethod",
    type: "select",
    // originField: "shippingService",
    // multiple: true,
    // collapseTags: true,
    // options: { placeholder: "平台运输方式" },
    style: { width: "280px" },
  },
  {
    field: "products.throw_rate",
    prepend: "抛率",
    type: "numberRange",
    precision: 2,
    style: { width: "280px" },
  },

  {
    field: "tracking_number_type",
    type: "select",
    origin: "tracking_number_type",
    options: { placeholder: "标记追踪号类型" },
    style: { width: "280px" },
  },

  { type: "title", label: "人员信息" },
  { field: "products.product_add_user_id", type: "cascader", emitPath: true, itemProps: { placeholder: "开发人员" } },
  { field: "products.reviewer_id", type: "cascader", emitPath: true, itemProps: { placeholder: "质检人员" } },
  { field: "products.img_processor_id", type: "cascader", emitPath: true, itemProps: { placeholder: "图片处理人员" } },
  { field: "products.purchasing_id", type: "cascader", emitPath: true, itemProps: { placeholder: "采购人员" } },
  { field: "customer_service_id", type: "cascader", emitPath: true, itemProps: { placeholder: "客服人员" } },
  { field: "create_user", type: "cascader", emitPath: true, itemProps: { placeholder: "添加人员" } },
])

export const fieldList = reactive([
  {
    field: "shopCascade",
    slot: "ShopCascade",
    multiple: true,
    type: "select",
    collapseTags: true,
  },
  {
    field: "order_status",
    type: "select",
    style: { width: "200px" },
    multiple: true,
    collapseTags: true,
    origin: "order_status",
    options: { placeholder: "订单状态" },
    show: () => orderStatusShow.value,
  },
  {
    field: "problem_cause_id",
    type: "select",
    style: { width: "210px" },
    origin: "order_question",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "问题原因" },
  },
  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    style: { width: "380px" },
    select: [
      { label: "下单时间", value: "order_time" },
      { label: "付款时间", value: "pay_time" },
      { label: "添加时间", value: "create_time" },
      { label: "发货时间", value: "shipping_time" },
      { label: "标发时间", value: "marking_time" },
      { label: "修改时间", value: "update_time" },
    ],
    options: { placeholder: "下单时间" },
  },

  {
    field: "pay_status",
    type: "select",
    origin: "payment_status",
    style: { width: "160px" },
    options: { placeholder: "是否付款" },
  },

  {
    field: "build_order_type",
    type: "select",
    origin: "build_order_type",
    options: { placeholder: "订单创建类型" },
    style: { width: "160px" },
  },
  {
    field: "shipping_type",
    type: "select",
    origin: "shipping_type",
    options: { placeholder: "订单发货类型" },
    style: { width: "160px" },
  },
  {
    field: "skuRange",
    placeholder: "可批量搜索",
    type: "textarea",
    style: { width: "200px" },
    select: [
      { label: "SKU", value: "products.sku" },
      { label: "自定SKU", value: "products.custom_sku" },
      { label: "赛盒SKU", value: "products.i_robot_box_sku" },
      { label: "渠道SKU", value: "products.platform_sku" },
      { label: "配货SKU", value: "products.distribution_skus.sku" },
      { label: "SPU", value: "products.spu" },
      { label: "ASIN", value: "products.asin" },
      { label: "商品中文名", value: "products.sku_cn_title" },
    ],
  },
  {
    field: "orderSnRange",
    placeholder: "可批量搜索",
    type: "textarea",
    style: { width: "240px" },
    selectStyle: { width: "140px" },
    select: [
      { label: "系统订单号", value: "order_sn" },
      { label: "平台订单号", value: "platform_order_sn" },
      { label: "交易号", value: "transaction_no" },
      { label: "海外仓出库单号", value: "overseas_wms_out_number" },
      { label: "买家姓名", value: "buyer_name" },
    ],
  },
  {
    field: "trackRange",
    placeholder: "可批量搜索",
    type: "textarea",
    style: { width: "240px" },
    selectStyle: { width: "128px" },
    select: [
      { label: "真实追踪号", value: "real_track_no" },
      { label: "物流商单号", value: "logistics_bill_num" },
      { label: "物流商转单号", value: "logistics_transfer_num" },
      { label: "标记追踪号", value: "tracking_number" },
      { label: "仓库包裹号", value: "parcel_no" },
      { label: "回邮单号", value: "return_number" },
    ],
  },
  {
    field: "mark_shipment_status",
    type: "select",
    origin: "mark_shipment_status",
    options: { placeholder: "标发状态" },
    multiple: true,
    collapseTags: true,
    style: { width: "180px" },
  },
  { field: "sales_id", type: "cascader", emitPath: true, itemProps: { placeholder: "销售人员" } },
  { field: "ship_warehouse_id", slot: "ShipWarehouse", type: "select", multiple: true, collapseTags: true },
  { field: "shipping_method_id", slot: "ShippingMethod", type: "select", multiple: true, collapseTags: true },
  {
    field: "recipient_country_id",
    slot: "RecipientCountry",
    type: "select",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "收货国家" },
  },
  {
    field: "ascription_extend",
    type: "select",
    origin: "ebay_site",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "ebay订单站点" },
    style: { width: "160px" },
  },
])

export const getSubmitForm = (formData) => {
  let newOptions = []
  // 多字段模块
  let selectFieldList = [...fieldList, ...highFieldList]
    .filter((v) => v.select && v.select.length)
    .map((v) => v.select)
    .flat()

  try {
    // console.warn("formData", formData)
    let formDatas = formData
    for (let field in formDatas) {
      let _val = formDatas[field]

      if (_val !== undefined) {
        let item = [...fieldList, ...highFieldList].find((n) => n.field === field)
        // 多字段模块
        if (!item) {
          let fieldData = selectFieldList.find((n) => n.value === field)
          if (fieldData) {
            item = {
              field: fieldData.value,
              type: "textarea",
            }
          }
          // 平台 站点 国家
          if (["platform_id", "site_id", "shop_id"].includes(field)) {
            item = {
              field: field,
              type: "select",
            }
          }
          // 订单排程策略  物流分仓策略
          if (["is_execute_order_strategy", "strategy_schedule_id", "is_execute_splitting_strategy", "splitting_strategy_id"].includes(field)) {
            item = {
              field: field,
              type: "select",
            }
          }
        }

        if (Object.prototype.toString.call(_val) === "[object Array]") {
          if (_val.length > 0) {
            let data = {
              field,
              value: _val,
            }
            if (["select", "selectV2"].includes(item.type)) {
              data.queryType = "terms"
            } else if (["cascader"].includes(item.type)) {
              data.queryType = "terms"
              if (Array.isArray(data.value?.[0])) {
                data.value = data.value.map((v) => v?.[v.length - 1])
              } else {
                data.value = data.value.filter(Boolean)
              }
            } else if (item.type === "dateTimeRangeNorm" || field.includes("_time")) {
              data = {
                ...data,
                queryType: "range",
                format: "yyyy-MM-dd HH:mm:ss",
                value: { gte: _val?.[0], lte: _val?.[1] },
              }
            }
            if (field.includes("products.")) {
              data.nested = true
            }

            if (data.hasOwnProperty("value")) {
              newOptions.push(data)
              continue
            }
          }
        }

        if (Object.prototype.toString.call(_val) === "[object Object]") {
          let data = { field }
          if (item.type === "numberRange") {
            if (_val.min || _val.max || _val.min == 0 || _val.max == 0) {
              data = { field: item.field, value: { gte: 0, lte: 0 }, queryType: "range" }
              _val.min && (data.value.gte = _val.min)
              _val.max && (data.value.lte = _val.max)
              if (data.field == "order_profitability") {
                data.value.gte = data.value.gte / 100
                data.value.lte = data.value.lte / 100
              }
            }
          } else if (item.scriptParams) {
            // 默认参数
            if (_val.default) {
              newOptions.push({ field, queryType: "script", value: _val.default })
            }
            data = {
              ...data,
              queryType: "script",
              value: { operate: _val?.script, val: _val?.val.includes(">") ? _val?.val.substr(1) : _val?.val },
            }
          } else if (!item?.select) {
            for (let item in _val) {
              const _v = _val[item]
              if ((Array.isArray(_v) && _v.length) || (!Array.isArray(_v) && _v)) {
                data = {
                  ...data,
                  queryType: "terms",
                  value: Array.isArray(_val[item]) ? _val[item] : [_val[item]],
                }
              }
            }
          }
          if (data.field.includes("products.")) {
            data.nested = true
          }

          if (data.hasOwnProperty("value")) {
            newOptions.push(data)
            continue
          }
        }

        if (["[object String]", "[object Number]"].includes(Object.prototype.toString.call(_val))) {
          if (_val === "") continue

          let data = {
            field,
            value: _val,
          }
          if (item?.special) {
            data.queryType = "special"
          }

          if (!item["field"]) {
            data.queryType = "special"
          }
          if (!item.type) {
            data.queryType = "term"
          }

          if (item.type === "textarea") {
            data.queryType = "terms"
            data.value = _val.split("\n").filter((v) => !!v.trim())
            data.value = data.value?.map((v) => v.trim())
            if (data.value.length) {
              // 商品中文名
              if (field == "products.sku_cn_title") {
                data.queryType = "match"
                data.value = data.value.join(" ")
              }
            }
          }

          if (item.type === "select") {
            data.queryType = "term"
          }

          if (data.field.includes("products.")) {
            data.nested = true
          }

          // pi 更改
          if (["documentary_time", "tracking_number_type"].includes(field)) {
            data.queryType = "combined_query"
          }

          if (data.hasOwnProperty("value")) {
            newOptions.push(data)
            continue
          }
        }
      }
    }
    // console.log(newOptions)
    return newOptions
  } catch (e) {
    console.error(e)
  }
}
